<?php

declare (strict_types = 1);

namespace app\admin\model\admin;

use app\common\model\admin\Menu as MenuModel;
use app\admin\model\admin\MenuApi as MenuApiModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 商家后台菜单模型
 * Class Menu
 */
class Menu extends MenuModel
{
    // 隐藏的字段
    protected $hidden = [
        // 'action_mark',
        // 'sort',
        // 'create_time',
        // 'update_time'
    ];

    /**
     * 根据菜单ID集获取列表
     * @param array $menuIds
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getListByIds(array $menuIds): array
    {
        // 菜单列表
        $list = static::getAll([['menu_id', 'in', $menuIds]],true);
        // 整理菜单绑定的apiID集
        return (new static)->getTreeData($list,0,false);
    }

    /**
     * 获取所有菜单列表
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */

    public static function getAllListByIds(): array
    {
        // 菜单列表
        $list = static::getAll([]);
        // 整理菜单绑定的apiID集
        return (new static)->getTreeData($list,0,false);
    }


    /**
     * 新增记录
     * @param array $data
     * @return bool
     */
    public function add(array $data): bool
    {
        $data['create_time'] = time();
        $data['update_time'] = time();
        return $this->save($data);
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edit(array $data): bool
    {
        // 判断上级角色是否为当前子级
        if (isset($data['pid']) && $data['pid'] > 0) {
            // 获取所有上级id集
            $parentIds = $this->getTopMenuIds($data['pid']);
            if (in_array($this['menu_id'], $parentIds)) {
                $this->error = '上级菜单不允许设置为当前子菜单';
                return false;
            }
        }
        // 如果模块是操作, 不允许修改上级菜单id
        if ($this['type'] == 20 && isset($data['pid'])) {
            unset($data['pid']);
        }
        $data['update_time'] = time();
        return $this->save($data);
    }

    /**
     * 设置菜单的API权限
     * @param array $data
     * @return bool|int
     */
    public function setApis(array $data): bool|int
    {
        if (!isset($data['apiIds'])) {
            $this->error = 'API权限不能为空';
            return false;
        }
        // 根据菜单id批量更新API关联记录
        return (new MenuApiModel)->updateByMenuId($this['menu_id'], $data['apiIds']);
    }

    /**
     * 删除菜单
     * @return bool
     */
    public function remove(): bool
    {
        // 判断是否存在下级菜单
        if (self::detail(['pid' => $this['menu_id']])) {
            $this->error = '当前菜单下存在子菜单或操作，请先删除';
            return false;
        }
        // 判断是否被分配有API接口
        if (MenuApiModel::detail(['menu_id' => $this['menu_id']])) {
            $this->error = '当前菜单下存在被分配接口，请先取消分配';
            return false;
        }
        // 删除
        return $this->delete();
    }

    /**
     * 获取所有上级id集
     * @param int $menuId
     * @param null $menuList
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function getTopMenuIds(int $menuId, $menuList = null): array
    {
        static $ids = [];
        is_null($menuList) && $menuList = $this->getAll();
        foreach ($menuList as $item) {
            if ($item['menu_id'] == $menuId && $item['pid'] > 0) {
                $ids[] = $item['pid'];
                $this->getTopMenuIds($item['pid'], $menuList);
            }
        }
        return $ids;
    }
}
